package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.atguigu.gulimall.member.utils.HttpUtils;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());

        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
//        System.out.println(vo.getPassWord());

        String encode = new BCryptPasswordEncoder().encode(vo.getPassWord());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
//        System.out.println(vo);
        String loginAcct = vo.getLoginAcct();
        String passWord = vo.getPassWord();
        MemberEntity entity = baseMapper.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, loginAcct).or().eq(MemberEntity::getUsername, loginAcct));
        if (entity == null) {
            System.out.println("2");
            return null;
        } else {
            System.out.println(passWord);
            System.out.println(entity.getPassword());
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(passWord, entity.getPassword());
            System.out.println(matches);
            return matches ? entity : null;
        }

    }

    @Override
    public MemberEntity oauthlogin(SocialUser vo) throws Exception {
        String uid = vo.getUid();
        MemberEntity member = baseMapper.selectOne(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getSocialUid, uid));
        if (member!=null) {
            // 已注册过
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(member.getId());
            memberEntity.setAccessToken(vo.getAccess_token());
            memberEntity.setExpiresIn(vo.getExpires_in());
            baseMapper.updateById(memberEntity);

            member.setAccessToken(vo.getAccess_token());
            member.setExpiresIn(vo.getExpires_in());
            return member;
        } else {
//            System.out.println("在这里");
            MemberEntity newMemberInfo = new MemberEntity();
            try {
//                System.out.println("在这里2");
                // 没注册，需要调用gitee接口查出用户信息
                Map<String, String> map = new HashMap<>();
                map.put("access_token",vo.getAccess_token());
//                System.out.println(vo.getAccess_token());
                HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", null, map);
//                System.out.println(response);
                if (response.getStatusLine().getStatusCode()==200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
//                    System.out.println("------------");
//                    System.out.println(name);
//                    System.out.println("------------");
                    newMemberInfo.setNickname(name);
                }
            } catch (Exception e) {}
            newMemberInfo.setSocialUid(vo.getUid());
            newMemberInfo.setAccessToken(vo.getAccess_token());
            newMemberInfo.setExpiresIn(vo.getExpires_in());
            baseMapper.insert(newMemberInfo);
            return newMemberInfo;
        }
    }

    private void checkUserNameUnique(String userName) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getUsername, userName));
        if (count>0) {
            throw new UsernameExistException("用户名已存在");
        }
    }

    private void checkPhoneUnique(String phone) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<MemberEntity>().eq(MemberEntity::getMobile, phone));
        if (count>0) {
            throw new UsernameExistException("手机号已存在");
        }
    }

}